package com.resume.aipeople.controller;

import com.resume.aipeople.entity.VoiceCache;
import com.resume.aipeople.repository.VoiceCacheRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 语音缓存管理控制器
 */
@RestController
@RequestMapping("/api/voice-cache")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class VoiceCacheController {
    
    private final VoiceCacheRepository voiceCacheRepository;
    
    /**
     * 获取语音缓存统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getCacheStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 总缓存数量
            long totalCount = voiceCacheRepository.countTotalVoices();
            stats.put("totalCount", totalCount);
            
            // 总缓存大小
            Long totalSize = voiceCacheRepository.getTotalCacheSize();
            stats.put("totalSizeBytes", totalSize != null ? totalSize : 0);
            stats.put("totalSizeMB", totalSize != null ? totalSize / (1024.0 * 1024.0) : 0);
            
            // 按角色统计
            Map<String, Long> characterStats = new HashMap<>();
            List<String> characters = List.of("哈利波特", "苏格拉底", "艾丽莎博士", "默认角色");
            for (String character : characters) {
                long count = voiceCacheRepository.countByCharacterName(character);
                if (count > 0) {
                    characterStats.put(character, count);
                }
            }
            stats.put("characterStats", characterStats);
            
            // 最常访问的语音
            List<VoiceCache> mostAccessed = voiceCacheRepository.findMostAccessedVoices();
            stats.put("mostAccessedCount", mostAccessed.size());
            
            // 最近访问的语音
            List<VoiceCache> recentlyAccessed = voiceCacheRepository.findRecentlyAccessedVoices();
            stats.put("recentlyAccessedCount", recentlyAccessed.size());
            
            return ResponseEntity.ok(stats);
            
        } catch (Exception e) {
            log.error("获取缓存统计失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取统计信息失败");
            return ResponseEntity.internalServerError().body(error);
        }
    }
    
    /**
     * 获取语音缓存列表（分页）
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getCacheList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "lastAccessedAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<VoiceCache> cachePage = voiceCacheRepository.findAll(pageable);
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", cachePage.getContent());
            response.put("totalElements", cachePage.getTotalElements());
            response.put("totalPages", cachePage.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            response.put("hasNext", cachePage.hasNext());
            response.put("hasPrevious", cachePage.hasPrevious());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取缓存列表失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取缓存列表失败");
            return ResponseEntity.internalServerError().body(error);
        }
    }
    
    /**
     * 根据角色获取语音缓存
     */
    @GetMapping("/by-character/{characterName}")
    public ResponseEntity<List<VoiceCache>> getCacheByCharacter(@PathVariable String characterName) {
        try {
            List<VoiceCache> caches = voiceCacheRepository.findByCharacterName(characterName);
            return ResponseEntity.ok(caches);
        } catch (Exception e) {
            log.error("根据角色获取缓存失败: {}", characterName, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取最常访问的语音缓存
     */
    @GetMapping("/most-accessed")
    public ResponseEntity<List<VoiceCache>> getMostAccessedVoices() {
        try {
            List<VoiceCache> caches = voiceCacheRepository.findMostAccessedVoices();
            return ResponseEntity.ok(caches);
        } catch (Exception e) {
            log.error("获取最常访问语音失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取最近访问的语音缓存
     */
    @GetMapping("/recently-accessed")
    public ResponseEntity<List<VoiceCache>> getRecentlyAccessedVoices() {
        try {
            List<VoiceCache> caches = voiceCacheRepository.findRecentlyAccessedVoices();
            return ResponseEntity.ok(caches);
        } catch (Exception e) {
            log.error("获取最近访问语音失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 清理过期的语音缓存
     */
    @DeleteMapping("/cleanup")
    public ResponseEntity<Map<String, Object>> cleanupExpiredCache(
            @RequestParam(defaultValue = "30") int daysToKeep) {
        try {
            LocalDateTime expiryDate = LocalDateTime.now().minusDays(daysToKeep);
            
            // 查找过期的缓存
            List<VoiceCache> expiredCaches = voiceCacheRepository.findExpiredVoices(expiryDate);
            
            // 删除过期的缓存
            voiceCacheRepository.deleteExpiredVoices(expiryDate);
            
            Map<String, Object> response = new HashMap<>();
            response.put("deletedCount", expiredCaches.size());
            response.put("expiryDate", expiryDate);
            response.put("message", "成功清理 " + expiredCaches.size() + " 个过期的语音缓存");
            
            log.info("清理过期语音缓存: 删除了 {} 个缓存", expiredCaches.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("清理过期缓存失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "清理过期缓存失败");
            return ResponseEntity.internalServerError().body(error);
        }
    }
    
    /**
     * 删除指定的语音缓存
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteCache(@PathVariable Long id) {
        try {
            Optional<VoiceCache> cacheOpt = voiceCacheRepository.findById(id);
            if (!cacheOpt.isPresent()) {
                Map<String, Object> error = new HashMap<>();
                error.put("error", "语音缓存不存在");
                return ResponseEntity.notFound().build();
            }
            
            VoiceCache cache = cacheOpt.get();
            voiceCacheRepository.deleteById(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "成功删除语音缓存");
            response.put("deletedId", id);
            response.put("characterName", cache.getCharacterName());
            response.put("textPreview", cache.getOriginalText().length() > 50 ? 
                cache.getOriginalText().substring(0, 50) + "..." : cache.getOriginalText());
            
            log.info("删除语音缓存: ID={}, 角色={}", id, cache.getCharacterName());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("删除语音缓存失败: ID={}", id, e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "删除语音缓存失败");
            return ResponseEntity.internalServerError().body(error);
        }
    }
    
    /**
     * 获取语音缓存详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<VoiceCache> getCacheDetail(@PathVariable Long id) {
        try {
            Optional<VoiceCache> cacheOpt = voiceCacheRepository.findById(id);
            if (cacheOpt.isPresent()) {
                VoiceCache cache = cacheOpt.get();
                // 更新访问信息
                cache.incrementAccessCount();
                voiceCacheRepository.save(cache);
                return ResponseEntity.ok(cache);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取语音缓存详情失败: ID={}", id, e);
            return ResponseEntity.internalServerError().build();
        }
    }
}
